package com.bawei.module_detail.ui

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_mvi.Router
import com.bawei.lib_common.base.utils.LoggerUtils
import com.bawei.lib_mvi.base.BaseMVIFragment
import com.bawei.lib_storage.mmkv.AuthMMKV
import com.bawei.module_detail.adapter.PlayListAdapter
import com.bawei.module_detail.databinding.FragmentProfileBinding
import com.bawei.module_detail.intent.VideoDetailIntent
import com.bawei.module_detail.state.VideoDetailState
import com.bawei.module_detail.viewmodel.VideoDetailViewModel
import kotlinx.coroutines.launch

private const val TAG = "ProfileFragment"

class ProfileFragment : BaseMVIFragment() {



    private lateinit var videoDetailViewModel: VideoDetailViewModel
    private val binding: FragmentProfileBinding by lazy {
        FragmentProfileBinding.inflate(layoutInflater)
    }
    private val playListAdapter = PlayListAdapter()
    private var mPosition = -1
    private var page = 1
    private var pageSize = 10
    override fun initView() {
        super.initView()
        val videoDetailText = AuthMMKV.videoDetailText
        if (videoDetailText.isNotEmpty()) {
            binding.playerProText.text = videoDetailText
        }
        binding.playerRv.adapter = playListAdapter
        binding.playerRv.layoutManager = LinearLayoutManager(requireContext())
    }

    override fun initData() {
        super.initData()
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                videoDetailViewModel.intents.send(
                    VideoDetailIntent.getVideoRecommend(
                        page,
                        pageSize
                    )
                )
            }
        }
        playListAdapter.setOnItemClickListener { adapter, view, position ->
            mPosition = position
            AuthMMKV.videoDetailIndex = mPosition
            playListAdapter.sendPosition(mPosition)
            playListAdapter.notifyDataSetChanged()
            ARouter.getInstance().build(Router.Ui.VIDEO_PLAY_DETAIL)
                .withSerializable("movie", playListAdapter.data[position]).navigation()
            activity?.finish()
        }
        val videoDetailIndex = AuthMMKV.videoDetailIndex
        if (videoDetailIndex != null) {
            playListAdapter.sendPosition(videoDetailIndex)
            playListAdapter.notifyDataSetChanged()
        }
    }

    override fun generateViewModel() {
        videoDetailViewModel = ViewModelProvider(this)[VideoDetailViewModel::class.java]
    }

    override fun lazyLoad() {

    }

    override fun getFragmentRootView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

        return binding.root
    }

    override fun handleState() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                videoDetailViewModel._videoDetailRecommendFlow.collect {
                    when (it) {
                        is VideoDetailState.Init -> {
                            LoggerUtils.d(TAG, "初始化成功")
                        }

                        is VideoDetailState.Empty -> {
                            LoggerUtils.d(TAG, "数据为空")
                        }

                        is VideoDetailState.Failed -> {
                            LoggerUtils.d(TAG, "请求失败")
                        }

                        is VideoDetailState.VideoRecommendSuccess -> {
                            Log.d(TAG, "handleState: ${it.list}")
                            playListAdapter.data.addAll(it.list!!)
                            playListAdapter.notifyDataSetChanged()
                        }

                        else -> {
                            LoggerUtils.d(TAG, "其他状态")
                        }
                    }
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        AuthMMKV.videoDetailIndex = 0
    }

    override fun onDestroyView() {
        super.onDestroyView()
        mView = null
    }

}